package com.mmall.common;

import com.mmall.util.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
    private static JedisPool pool;//jedis连接池
    private static Integer MaxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));//最大连接数
    private static Integer Minidle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2"));//最小连空闲数量
    private static Integer Maxidle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10"));//最大连空闲数量

    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.brrow", "true"));//在进行jedis连接操作的时候是否验证连接可用
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.retrun", "true"));//在进行jedis返回操作的时候是否验证连接可用

    private static Integer Prot = Integer.parseInt(PropertiesUtil.getProperty("redis.prot", "6379"));
    private static String Ip = PropertiesUtil.getProperty("redis.ip", "127.0.0.1");

    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(MaxTotal);
        config.setMaxIdle(Maxidle);
        config.setMinIdle(Minidle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true);//连接阻塞时是否超时,true阻塞直到超时.false返回连接错误

        pool = new JedisPool(config, Ip, Prot, 1000 * 2);
    }

    static {
        initPool();
    }

    public static Jedis getjedis() {
        return pool.getResource();
    }

    public static void returnBrokenResource(Jedis jedis) {
        pool.returnBrokenResource(jedis);
    }

    public static void retrunResource(Jedis jedis) {
        pool.returnResource(jedis);
    }


    public static void main(String[] args) {
        Jedis jedis = pool.getResource();
        jedis.set("key1", "key1");
        retrunResource(jedis);
        pool.destroy();//临时调用
        System.out.println("程序运行结束");
    }
}


